#include "dictdatadlg.h"
#include "dictionarymanager.h"
#include "editdictionary.h"

#include <QMouseEvent>

DictionaryManager::DictionaryManager(Ui::Index *ui,QObject *parent)
    : QObject{parent}
{
    this->ui = ui;
    //图标
    QPixmap pix(":/image/res/search.jpg");
    pix.scaled(25,25);
    ui->btn_dictionaryManager_hideSearch->setIcon(pix);
    ui->btn_dictionaryManager_search->setIcon(pix);
    QPixmap freshPix(":/image/res/refresh.jpg");
    ui->btn_dictionaryManager_reset->setIcon(freshPix.scaled(25,25));
    ui->btn_dictionaryManager_refresh->setIcon(freshPix.scaled(25,25));
    ui->tableWidget_dictionaryManager->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui->tableWidget_dictionaryManager->setSelectionBehavior(QAbstractItemView::SelectRows);

    init();

    //隐藏搜索
    connect(ui->btn_dictionaryManager_hideSearch,&QPushButton::clicked,this,[=](){
        ui->widget_49->setHidden(!ui->widget_49->isHidden());
    });
//    //下一页
    connect(ui->btn_dictionaryManager_next,&QPushButton::clicked,this,[=](){
        ui->btn_dictionaryManager_next->setEnabled(0);
        currentPage ++;
        getList();
        initTable();
        initPageInfo();
    });
    //上一页
    connect(ui->btn_dictionaryManager_pervious,&QPushButton::clicked,this,[=](){
        ui->btn_dictionaryManager_pervious->setEnabled(0);
        currentPage --;
        getList();
        initTable();
        initPageInfo();
    });
    //跳转页
    connect(ui->lineEdit_dictionaryManager_gotoPage,&QLineEdit::returnPressed,this,[=](){
        int page = ui->lineEdit_dictionaryManager_gotoPage->text().toInt();
        ui->lineEdit_dictionaryManager_gotoPage->clear();
        if(page < 1 || page > totalPage){
            ui->lineEdit_dictionaryManager_gotoPage->setStyleSheet("border:1px solid red;");
            return;
        }
        ui->lineEdit_dictionaryManager_gotoPage->setStyleSheet("");
        currentPage = page;
        getList();
        initTable();
        initPageInfo();
    });
//    每页大小
    connect(ui->comboBox_dictionaryManager_pageItem,SIGNAL(currentIndexChanged(int)),this,SLOT(pageSizeChanged(int)));
//    重置
    connect(ui->btn_dictionaryManager_reset,&QPushButton::clicked,this,[=](){
        ui->btn_dictionaryManager_reset->setEnabled(0);
        init();
        ui->btn_dictionaryManager_reset->setEnabled(1);
    });
    //搜索
    connect(ui->btn_dictionaryManager_search,&QPushButton::clicked,this,[=](){
        getList();
        initTable();
        initPageInfo();
    });
    //刷新
    connect(ui->btn_dictionaryManager_refresh,&QPushButton::clicked,this,[=](){
        getList();
        initTable();
        initPageInfo();
    });
    connect(ui->btn_dictionaryManager_add,&QPushButton::clicked,this,[=](){
        EditDictionary *e = new EditDictionary(-1);
        e->setAttribute(Qt::WA_DeleteOnClose);
        connect(e,&EditDictionary::success,this,[=](){
            getList();
            initTable();
            initPageInfo();
        });
        e->exec();
    });
    //修改
    connect(ui->btn_dictionaryManager_update,&QPushButton::clicked,this,[=](){
        int index = ui->tableWidget_dictionaryManager->currentRow();
        if(index < 0) return;
        QString id = ui->tableWidget_dictionaryManager->item(index,0)->text();
        EditDictionary e(id.toLong());
        connect(&e,&EditDictionary::success,this,[=](){
            getList();
            initTable();
            initPageInfo();
        });
        e.exec();
    });
    //批量删除
    connect(ui->btn_dictionaryManager_del,SIGNAL(clicked()),this,SLOT(deleteByIds()));
    //导出
    connect(ui->btn_dictionaryManager_export,&QPushButton::clicked,this,[=](){
        utils.exportExcel(ui->tableWidget_dictionaryManager,"字典管理表格");
    });
    connect(ui->btn_dictionaryManager_refreshCache,&QPushButton::clicked,this,[=](){
        QByteArray *bytes = dictionaryManagerApi.refreshCache();
        QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
        QMessageBox::warning(0,"提示",obj.value("msg").toString());
    });
}

bool DictionaryManager::eventFilter(QObject *obj, QEvent *event)
{
    //mouse button pressed
    if (event->type() == QEvent::MouseButtonPress){
        QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
        if(mouseEvent->button() == Qt::LeftButton){
            return true;
        }else{
            return false;
        }
    }
    return true;
}

void DictionaryManager::pageSizeChanged(int index)
{
    switch (index) {
    case 0:
        pageSize = 5;
        break;
    case 1:
        pageSize = 10;
        break;
    case 2:
        pageSize = 20;
        break;
    case 3:
        pageSize = 50;
        break;
    case 4:
        pageSize = 100;
        break;
    default:
        break;
    }
    currentPage = 1;
    getList();
    initTable();
    initPageInfo();
}

void DictionaryManager::deleteByIds()
{
    QList<QTableWidgetItem*> items = ui->tableWidget_dictionaryManager->selectedItems();
    if(items.size() == 0) return;
    int rowCount = items.size() / 4;    //选中的行数
    QString ids;
    for(int i = 0;i< rowCount;i++){
        int index = ui->tableWidget_dictionaryManager->row(items.at(i * 4));
        if(i != rowCount - 1){
            ids += ui->tableWidget_dictionaryManager->item(index,0)->text() + ",";
        }else{
            ids += ui->tableWidget_dictionaryManager->item(index,0)->text();
        }
    }
    int flag = QMessageBox::question(0,"提示","确定删除所选项吗?",QMessageBox::Yes|QMessageBox::No);
    if(flag == QMessageBox::No) return;
    QByteArray *bytes = dictionaryManagerApi.deleteItems(ids);
    QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
    if(200 == obj.value("code").toInt()){
        QMessageBox::warning(0,"提示",obj.value("msg").toString());
        getList();
        initTable();
        initPageInfo();
    }
}

void DictionaryManager::init()
{
    getDictList();
    initSearchArea();
    getList();
    initTable();
    initPageInfo();
}

void DictionaryManager::getDictList()
{
    dictList.clear();
    QByteArray *data = utils.getDictType("sys_normal_disable");
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    QJsonArray arr = obj.value("data").toArray();
    for(int i = 0;i< arr.size();i++){
        dictList.append(DictData::toDictData(arr.at(i).toObject()));
    }
}

void DictionaryManager::initSearchArea()
{
    ui->lineEdit_dictionaryManager_dictionaryName->clear();
    ui->lineEdit_dictionaryManager_dictionaryType->clear();
    ui->comboBox_dictionaryManager_status->clear();
    ui->comboBox_dictionaryManager_status->addItem("");
    for(int i = 0;i< dictList.size();i++){
        ui->comboBox_dictionaryManager_status->addItem(dictList.at(i).dictLabel,dictList.at(i).dictValue);
    }
    ui->dateEdit_dictionaryManager_start->setDate(QDate(2000,1,1));
    ui->dateEdit_dictionaryManager_end->setDate(QDate(2000,1,1));
}

void DictionaryManager::getList()
{
    dictTypeList.clear();
    QString type = ui->lineEdit_dictionaryManager_dictionaryType->text();
    QString status = ui->comboBox_dictionaryManager_status->itemData(
                ui->comboBox_dictionaryManager_status->currentIndex()).value<QString>();
    QString dName = ui->lineEdit_dictionaryManager_dictionaryName->text();
    QString start = ui->dateEdit_dictionaryManager_start->text();
    QString end = ui->dateEdit_dictionaryManager_end->text();
    QByteArray *data = dictionaryManagerApi.getList(currentPage,pageSize,dName,type,status,start,end);
    QJsonObject obj = QJsonDocument::fromJson(*data).object();
    QJsonArray arr = obj.value("rows").toArray();
    total = obj.value("total").toInt();
    for(int i = 0;i< arr.size();i++){
        dictTypeList.append(DictType::toDictType(arr.at(i).toObject()));
    }
    if(total%pageSize == 0){
        totalPage = total / pageSize;
    }else{
        totalPage = total / pageSize + 1;
    }
    ui->label_dictionaryManager_count->setText("共"+QString::number(total)+"条");
}

void DictionaryManager::initTable()
{
    ui->tableWidget_dictionaryManager->clear();
    QStringList columnHeader;
    columnHeader << "字典编号" << "字典名称" << "字典类型" << "状态" << "备注" << "创建时间" << "操作";
    ui->tableWidget_dictionaryManager->setColumnCount(columnHeader.size());
    ui->tableWidget_dictionaryManager->setHorizontalHeaderLabels(columnHeader);
    ui->tableWidget_dictionaryManager->setRowCount(dictTypeList.size());
    ui->tableWidget_dictionaryManager->setColumnWidth(2,150);
    ui->tableWidget_dictionaryManager->setColumnWidth(5,150);
    ui->tableWidget_dictionaryManager->setColumnWidth(6,165);
    for(int i = 0;i< dictTypeList.size();i++){
        ui->tableWidget_dictionaryManager->setRowHeight(i,38);
        QString dictionaryId = QString::number(dictTypeList.at(i).dictId);
        ui->tableWidget_dictionaryManager->setItem(i,0,new QTableWidgetItem(dictionaryId));
        ui->tableWidget_dictionaryManager->setItem(i,1,new QTableWidgetItem(dictTypeList.at(i).dictName));

        QLabel *labelType = new QLabel();
        connect(labelType,&QLabel::linkActivated,this,[=](){
            DictDataDlg *d = new DictDataDlg(dictTypeList.at(i).dictId,dictList,dictTypeList.at(i).dictType);
            d->setAttribute(Qt::WA_DeleteOnClose);
            d->exec();
        });
//        labelType->setStyleSheet("text-decoration: none;");
        labelType->setCursor(Qt::PointingHandCursor);
//        labelType->setText("<a href='www.baidu.com'>" + dictTypeList.at(i).dictType + "</a>");
        labelType->setText("<style>a { text-decoration: none; }</style><a href=\"https://www.example.com\"><u>" + dictTypeList.at(i).dictType + "</u></a>");
        labelType->setAlignment(Qt::AlignCenter);
        labelType->setStyleSheet("QLabel:hover {color: rgb(24, 144, 255);background-color: white;}QLabel:pressed {color: rgb(24, 144, 255);background-color: white;}QLabel {color: rgb(24, 144, 150);background-color: white;font: 10pt Microsoft YaHei UI;}");
        QWidget *widgetType = new QWidget();
        QHBoxLayout* hLayoutType = new QHBoxLayout(widgetType);
        // 设置QLabel的对齐方式为居中
        labelType->setAlignment(Qt::AlignCenter);
        // 将QLabel添加到QHBoxLayout和QVBoxLayout
        hLayoutType->addWidget(labelType);
        ui->tableWidget_dictionaryManager->setCellWidget(i,2,widgetType);

        QLabel *label = new QLabel();
        label->setText(dictTypeList.at(i).status == "0" ? "正常" : "停用");
        label->setFixedSize(46,20);
        label->setAlignment(Qt::AlignCenter);
        label->setStyleSheet(dictTypeList.at(i).status == "0" ?
                                 "background-color:rgb(230, 242, 253);color:rgb(24, 144, 255);border:1px solid rgb(209,233,255);border-radius:3px;" :
                                 "background-color:rgb(255, 237, 237);color:rgb(255, 73, 73);border:1px solid rgb(255,219,219);border-radius:3px;");
        QWidget *widget = new QWidget();
        QHBoxLayout* hLayout = new QHBoxLayout(widget);
        // 设置QLabel的对齐方式为居中
        label->setAlignment(Qt::AlignCenter);
        // 将QLabel添加到QHBoxLayout和QVBoxLayout
        hLayout->addWidget(label);
        ui->tableWidget_dictionaryManager->setCellWidget(i,3,widget);
        ui->tableWidget_dictionaryManager->setItem(i,4,new QTableWidgetItem(dictTypeList.at(i).remark));
        ui->tableWidget_dictionaryManager->setItem(i,5,new QTableWidgetItem(dictTypeList.at(i).createTime));
        QWidget *tmp_widget = new QWidget();
        QHBoxLayout *tmp_layout = new QHBoxLayout();
        QPushButton *btnUpdate = new QPushButton;
        QPushButton *btnDelete = new QPushButton;
        connect(btnDelete,&QPushButton::clicked,this,[=](){
            int flag  = QMessageBox::question(0,"提示","确定删除该项吗?",QMessageBox::Yes|QMessageBox::No);
            if(flag == QMessageBox::Yes){
                if(flag == QMessageBox::No) return;
                QByteArray *bytes = dictionaryManagerApi.deleteItems(dictionaryId);
                QJsonObject obj = QJsonDocument::fromJson(*bytes).object();
                if(200 == obj.value("code").toInt()){
                    QMessageBox::warning(0,"提示",obj.value("msg").toString());
                    getList();
                    initTable();
                    initPageInfo();
                }
            }
        });
        connect(btnUpdate,&QPushButton::clicked,this,[=](){;
            EditDictionary *e = new EditDictionary(dictionaryId.toLongLong());
            connect(e,&EditDictionary::success,this,[=](){
                getList();
                initTable();
                initPageInfo();
            });
            e->exec();
        });
        btnDelete->setText("🗑删除");
        btnDelete->setFixedSize(80,35);
        btnUpdate->setText("🖍修改");
        btnUpdate->setFixedSize(80,35);
        btnUpdate->setStyleSheet("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(231, 250, 240);color: black;}QPushButton:hover {background-color: rgb(19, 206, 102);}QPushButton:pressed {background-color: rgb(19, 150, 102);}");
        btnDelete->setStyleSheet("QPushButton {padding: 5px 10px;border-style: none;border-radius: 10px;background-color: rgb(232, 244, 255);color: black;}QPushButton:hover {background-color: rgb(24, 144, 255);}QPushButton:pressed {background-color: rgb(24, 144, 200);}");
        tmp_layout->addWidget(btnUpdate);
        tmp_layout->addWidget(btnDelete);
        tmp_widget->setLayout(tmp_layout);
        tmp_layout->setMargin(0);
        ui->tableWidget_dictionaryManager->setCellWidget(i,6,tmp_widget);
    }
    // 设置单元格内容居中对齐
    for (int row = 0; row < ui->tableWidget_dictionaryManager->rowCount(); ++row) {
        for (int column = 0; column < ui->tableWidget_dictionaryManager->columnCount(); ++column) {
            QTableWidgetItem* item = ui->tableWidget_dictionaryManager->item(row, column);
            if (item) {
                item->setTextAlignment(Qt::AlignCenter);
            }
        }
    }
}

void DictionaryManager::initPageInfo()
{
    if(currentPage == 1){
        ui->btn_dictionaryManager_pervious->setEnabled(0);
    }else{
        ui->btn_dictionaryManager_pervious->setEnabled(1);
    }
    ui->label_dictionaryManager_currentPage->setText(QString::number(currentPage));
    if(currentPage == totalPage){
        ui->btn_dictionaryManager_next->setEnabled(0);
    }else{
        ui->btn_dictionaryManager_next->setEnabled(1);
    }
}
